package com.Controller;

import com.Service.UserService;
import com.config.SpringConfig;
import com.domain.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    UserService cs= (UserService)ctx.getBean(UserService.class);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        //获取请求参数请
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //创建对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);

        User user = cs.findId(loginUser);
        //正确判断用户名密码是否正确
            if (user == null) {
                //不正确,储存提示消息
                resp.getWriter().write("false");
            } else {
                //登录成功
                req.getSession().setAttribute("username",user.getUsername());
                resp.getWriter().write("true");
            }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
